home *** CD-ROM | disk | FTP | other *** search
- Path: news.iag.net!news
- From: jatmon@iag.net (John R Buchan)
- Newsgroups: comp.lang.c
- Subject: Re: why get 9 strings only?
- Date: 24 Jan 1996 15:53:40 GMT
- Organization: Internet Access Group, Orlando, Florida
- Message-ID: <4e5km4$2e6@news.iag.net>
- References: <4e51th$4bi@news.nevada.edu>
- NNTP-Posting-Host: pm2-orl16.iag.net
- X-Newsreader: WinVN 0.99.7
-
- In article <4e51th$4bi@news.nevada.edu>, chancl@nevada.edu says...
- >
- >I can't figure out why I can only input 9 strings
- >instead of 10 on the following program:
- >
- >**************************************************************
- >
- >/* Write a program that reads a number and then a list of */
- >/* strings (all on separate lines), and then prints one of */
- >/* the lines from the list as selected by the number. */
- >
- >#include <stdio.h>
- >
- >void main()
-
- In anci c code, main must return int. A return of void is undefined.
-
- >{
- > char str[10][80];
- > int i, j;
- >
- > printf("Enter a number (0-9):\n");
- > scanf("%d", &j);
-
- Using scanf for input to input numeric values is tricky. Here you've
- told it to read an integer value and store it in j. It obediently
- reads chars until it reaches the first one that isn't allowed for ints.
- In this case probably a '\n'. It leaves the unused char in the buffer,
- converts the read chars, and stores the value in j.
-
- >
- > printf("Enter 10 strings:\n");
- > for(i=0; i<10; i++) /* get 10 strings */
- > gets(str[i]); /* but can input 9 strings */
-
- gets reads any chars in the input buffer for stdin (reading, but not
- storing any '\n'). On the first iteration of the loop, it will read
- what was left in the buffer by the earlier scanf (there must at least
- be a '\n' in the buffer). Then it will begin reading your input lines.
-
- To see this either watch your str[0] while stepping through in a debugger
- or add a printf( "Input string %d is: %s\n", i, str[i]); in your for loop.
-
- BTW, you should use fgets( str[i], sizeof(str[0]), stdin) instead of your
- gets statement. It will protect your array bounds.
-
- A common solution to the scanf problem is to ise fgets to input a line
- from the user, then sscanf, atoi, etc to parse it.
-
- >
- > if(j>0 && j<10)
- > printf("Answer: %s\n", str[j]);
- >}
-
- --
- John R Buchan -:|:- Looking for that elusive FAQ? ftp to:
- jatmon@mail.iag.net -:|:- rtfm.mit.edu /pub/usenet-by-group/....
-
-